﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlsugarService.Infrastructure.Services;

namespace SqlsugarService.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DatabaseController : ControllerBase
    {
        private readonly DatabaseInitializationService _databaseService;
        private readonly ILogger<DatabaseController> _logger;

        public DatabaseController(
            DatabaseInitializationService databaseService,
            ILogger<DatabaseController> logger)
        {
            _databaseService = databaseService;
            _logger = logger;
        }

        /// <summary>
        /// 检查数据库连接状态
        /// </summary>
        /// <returns>数据库连接状态</returns>
        [HttpGet("health")]
        public async Task<IActionResult> CheckHealth()
        {
            var isHealthy = await _databaseService.CheckDatabaseConnectionAsync();
            return Ok(new { IsHealthy = isHealthy, Timestamp = DateTime.UtcNow });
        }

        /// <summary>
        /// 获取所有表名
        /// </summary>
        /// <returns>数据库中所有表的列表</returns>
        [HttpGet("tables")]
        public async Task<IActionResult> GetTables()
        {
            var tables = await _databaseService.GetAllTablesAsync();
            return Ok(new { Tables = tables, Count = tables.Count });
        }

        /// <summary>
        /// 手动初始化数据库表
        /// </summary>
        /// <param name="forceRecreate">是否强制重新创建表（会删除现有数据）</param>
        /// <returns>初始化结果</returns>
        [HttpPost("initialize")]
        public async Task<IActionResult> InitializeTables([FromQuery] bool forceRecreate = false)
        {
            try
            {
                _logger.LogWarning($"手动初始化数据库表请求 - ForceRecreate: {forceRecreate}");

                if (forceRecreate)
                {
                    _logger.LogWarning("警告：强制重新创建表将删除所有现有数据！");
                }

                var success = await _databaseService.InitializeTablesAsync(forceRecreate);

                if (success)
                {
                    return Ok(new
                    {
                        Success = true,
                        Message = "数据库表初始化成功",
                        ForceRecreate = forceRecreate,
                        Timestamp = DateTime.UtcNow
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "数据库表初始化失败",
                        Timestamp = DateTime.UtcNow
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据库表初始化异常");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "数据库表初始化异常",
                    Error = ex.Message,
                    Timestamp = DateTime.UtcNow
                });
            }
        }
    }
}
